// 将 params 字符串解析为对象，并返回
function parse_params(params) {
    return params.split('&').reduce(function (prev, cur) {
        var [key, value] = cur.split('=')
        // decodeURIComponent, decodeURI 都是解码字符串
        // 如果有特殊字符（&，#，/），只能用 decodeURIComponent
        prev[key] = decodeURIComponent(value)
        return prev
    }, {})
}

(function () {
    var template = {
        'sNo|+1': 1,
        name: '@cname',
        sex: '@pick(["男", "女"])',
        email: '@email',
        age: '@natural(10,80)',
        phone: /^1[3-9]\d{9}$/,
        address: '@county(true)',
    }
    var stu_data = null

    Mock.mock('/stu_list', function () {
        if (localStorage.getItem('stu_data')) {
            // 本地有数据，返回本地数据
            stu_data = JSON.parse(localStorage.getItem('stu_data'))
        } else {
            // 没有数据，先生成数据，再存储到本地
            stu_data = Mock.mock({ "data|5-15": [template] }).data
            localStorage.setItem('stu_data', JSON.stringify(stu_data))
        }
        return stu_data
    })

    Mock.mock('/stu_del', function (data) {
        var id = parse_params(data.body).id
        var status = null;
        stu_data.forEach(function (item, index) {
            if (item.sNo == id) {
                stu_data.splice(index, 1)
                localStorage.setItem('stu_data', JSON.stringify(stu_data))
                status = 'success'
            }
        })
        if (status === 'success') {
            return { status }
        } else {
            return { status: 'fail', msg: '没有找到此学生' }
        }
    })


    Mock.mock('/stu_change', function (data) {
        var param_obj = parse_params(data.body)
        var id = param_obj.id
        var params = parse_params(param_obj.params)
        stu_data.forEach(function (item) {
            if (item.sNo == id) {
                item.name = params.name
                item.sex = params.sex
                item.age = params.age
                item.email = params.email
                item.phone = params.phone
                item.address = params.address
            }
        })
        localStorage.stu_data = JSON.stringify(stu_data)
        return { status: 'success' }
    })

    Mock.mock('/stu_add', function(data){
        var param_obj = parse_params(data.body)
        var sNo = stu_data[stu_data.length-1].sNo
        param_obj.sNo = sNo + 1
        stu_data.push(param_obj)
        localStorage.stu_data = JSON.stringify(stu_data)
        return {status: 'success', data: param_obj}
    })

    Mock.mock('/stu_add_random', function(){
        var sNo = stu_data[stu_data.length-1].sNo
        var param_obj = Mock.mock(template)
        param_obj.sNo = sNo + 1
        stu_data.push(param_obj)
        localStorage.stu_data = JSON.stringify(stu_data)
        return {status: 'success', data: param_obj}
    })
})()